package com.main.service.impl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.main.bo.LoginBO;
import com.main.common.R;
import com.main.mapper.UserMapper;
import com.main.pojo.User;
import com.main.service.UserService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务实现类
 *
 * @author RuoYu
 * @date 2022/09/26
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @CreateCache(area = "sms", name = "user_", expire = 300, timeUnit = TimeUnit.SECONDS)
    private Cache<String, String> jetCache;


    /**
     * 账户登录
     *
     * @param userLoginInformation 用户登录信息
     * @param password             密码
     * @param request              请求
     * @return {@link LoginBO}
     */
    @Override
    public LoginBO accountLogin(User userLoginInformation, String password, HttpServletRequest request) {

        String phone = userLoginInformation.getPhone();
        String email = userLoginInformation.getEmail();
        String userName = userLoginInformation.getUserName();


        log.info("phone{},email{},username{},password,{}", phone, email, userName, password);

        //手机号登录
        if (phone != null && email == null && userName == null) {
            log.info("手机号登录");
            LoginBO<User> phoneValue = accountType(userLoginInformation, password);
            if (phoneValue.getMsg() != null) {
                return LoginBO.error(phoneValue.getMsg());
            }
            request.getSession().setAttribute("user", phoneValue.getData().getId());
            return phoneValue;
        }
        //邮箱登录
        if (phone == null && email != null && userName == null) {
            log.info("邮箱登录");
            LoginBO<User> emailValue = accountType(userLoginInformation, password);
            if (emailValue.getMsg() != null) {
                return LoginBO.error(emailValue.getMsg());
            }
            request.getSession().setAttribute("user", emailValue.getData().getId());
            return emailValue;
        }
        //用户名登录
        if (phone == null && email == null && userName != null) {
            log.info("用户名登录");
            LoginBO<User> userValue = accountType(userLoginInformation, password);
//            log.info("userValue:{}", userValue);

            //账号错误信息
            if (userValue.getMsg() != null) {
                return LoginBO.error(userValue.getMsg());
            }

            request.getSession().setAttribute("user", userValue.getData().getId());
            return userValue;
        }
        return LoginBO.error("系统繁忙！");
    }

    public LoginBO<User> accountType(User accountType, String password) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        //用户名
        lqw.eq(StringUtils.isNoneEmpty(accountType.getUserName()), User::getUserName, accountType.getUserName());
        //邮箱
        lqw.eq(StringUtils.isNoneEmpty(accountType.getEmail()), User::getEmail, accountType.getEmail());
        //手机号
        lqw.eq(StringUtils.isNoneEmpty(accountType.getPhone()), User::getPhone, accountType.getPhone());
        //指定查询字段，防止信息泄露
        lqw.select(User::getId, User::getUserName, User::getEmail, User::getPassword, User::getPhone, User::getStatus);

        User one = userMapper.selectOne(lqw);
        System.out.println(one);
        if (one == null) {
            return LoginBO.error("账户不存在");
        }
//        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!one.getPassword().equals(password)) {
            return LoginBO.error("密码错误");
        }

        if (one.getStatus() == 0) {
            return LoginBO.error("账户已被禁用，请联系管理员!");
        }

        //不把密码信息 返回显示
        one.setPassword(null);
        return LoginBO.success(one);
    }

    /**
     * 电子邮件快速登录
     *
     * @param mail        邮件
     * @param mailCaptcha 邮件验证码
     * @return {@link String}
     */
    @Override
    public LoginBO EmailQuickLogin(String mail, String mailCaptcha, HttpServletRequest request) {
        //1、取出redis中验证码
        String codeCache = jetCache.get(mail);

        //2、验证码是否为空？是否正确？
        if (mailCaptcha != null && mailCaptcha.equals(codeCache)) {
            //3、清除redis中对应验证码
            boolean remove = jetCache.remove(mail);

            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getEmail, mail);
            User user = userMapper.selectOne(lqw);

            //4.1、当前是否为新用户？
            if (user == null) {
                user = new User();
                user.setEmail(mail);
                String s = UUID.randomUUID().toString();
                user.setUserName(s.substring(0, 8));

                //上线时切记打开！！！！！！
//                user.setPassword(DigestUtils.md5DigestAsHex(s.getBytes()));

                //开发阶段使用（123456）默认密码
                user.setPassword("123456");

                System.out.println(user);
                userMapper.insert(user);
                log.info("新用户");
            } else if (user.getStatus() == 0) {//4.2老用户账号状态是否正常
                return LoginBO.error("账户已被禁用，请联系管理员!");
            }

            request.getSession().setAttribute("user", user.getId());

            //5、不把密码信息 返回显示
            user.setPassword(null);
            return LoginBO.success(user);
        }
        return LoginBO.error("验证码错误");
    }

    /**
     * 手机快速登录
     *
     * @param phoneCode    电话号码
     * @param phoneCaptcha 手机验证码
     * @return {@link String}
     */
    @Override
    public LoginBO PhoneQuickLogin(String phoneCode, String phoneCaptcha, HttpServletRequest request) {
        return null;
    }

    /**
     * 更新用户密码
     *
     * @param user 用户
     * @return boolean
     */
    @Override
    public boolean updateUserPassword(User user) {
        System.out.println(user.getId() + "--------------" + user.getPassword());
        int b = userMapper.updateUserPassword(user);
        System.out.println(b + "--------------");
        return b != 0;
    }
}
